package com.jinbiao.quasar.handler;

import cn.hutool.http.Header;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import com.jinbiao.quasar.annotate.LoginLog;
import com.jinbiao.quasar.dto.LoginDto;
import com.jinbiao.quasar.model.SysLogLogin;
import com.jinbiao.quasar.util.AjaxJson;
import org.noear.solon.Solon;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;

import java.io.IOException;

public class LoginLogHandler implements Handler {
    @Db
    SqlToyLazyDao dao;
    @Override
    public void handle(Context ctx) throws Throwable {
        new Runnable() {
            @Override
            public void run() {
                LoginDto loginDto = null;
                try {
                    loginDto = JSONUtil.toBean(ctx.body(), LoginDto.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                SysLogLogin logLogin = new SysLogLogin();
                logLogin.setLoginIp(ctx.ip());
                UserAgent ua = UserAgentUtil.parse(ctx.userAgent());
                logLogin.setLoginPlatform(ua.getPlatform().getName());
                logLogin.setLoginOs(ua.getOs().getName());
                logLogin.setLoginBrowser(ua.getBrowser().getName()+" "+ua.getBrowser().getVersion(ctx.userAgent()));
                logLogin.setLoginUsername(loginDto.getUsername());
                AjaxJson result = (AjaxJson) ctx.result;
                if(result.getCode()==200){
                    logLogin.setLoginSuccess("yesNo_yes");
                    logLogin.setMemo("登录成功;"+ctx.userAgent());
                }else{
                    logLogin.setLoginSuccess("yesNo_no");
                    logLogin.setMemo("登录失败;"+ctx.userAgent());
                }
                logLogin.setStable("yesNo_no");
                logLogin.setSort(1);
                dao.save(logLogin);
            }
        }.run();
    }
}
